package cn.dakaqi.web.api.v2;

import cn.dakaqi.activity.services.ActivityDao;
import cn.dakaqi.entities.Activity;
import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.User;
import cn.dakaqi.entities.Volunteer;
import cn.dakaqi.group.services.GroupDao;
import cn.dakaqi.group.services.GroupVolunteerDao;
import cn.dakaqi.member.service.VolunteerDao;
import cn.dakaqi.user.service.AccountDao;
import cn.dakaqi.utils.BaseDAO;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springside.modules.utils.Clock;

import java.text.ParseException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/26.
 */
public class ImportData implements Runnable
{
    BaseDAO baseDAO;
    AccountDao accountDao;
    VolunteerDao volunteerDao;
    GroupDao groupDao;
    GroupVolunteerDao groupVolunteerDao;
    ActivityDao activityDao;

    Map<String,String> volID_OLDID_NEWID = new HashMap<String, String>();
    Map<String,String> orgID_OLDID_NEWID = new HashMap<String, String>();
    Map<String,String> actID_OLDID_NEWID = new HashMap<String, String>();

    RedisClientTemplate redisClientTemplate = null;


    public ImportData()
    {
    }

    public ImportData(RedisClientTemplate redisClientTemplate,BaseDAO baseDAO,AccountDao accountDao,VolunteerDao volunteerDao,GroupDao groupDao,GroupVolunteerDao groupVolunteerDao,ActivityDao activityDao)
    {
        this.baseDAO = baseDAO;
        this.accountDao = accountDao;
        this.volunteerDao = volunteerDao;
        this.groupDao = groupDao;
        this.groupVolunteerDao = groupVolunteerDao;
        this.activityDao = activityDao;
        this.redisClientTemplate = redisClientTemplate;
    }


    @Override
    public void run()
    {
        importMember();
        //importGroup();
        //importActivity();
    }

    /**********************************************************/
    private void importActivity()
    {
//        long totalNumber = 0,numberPage = 200000,page = 0;
//        String sql = "select count(id) as c from volunteer_pu.member where delStatus=0";
//        List<Map<String, Long>> list = this.queryNativeSql(sql);
//        for (Map<String, Long> map : list)
//        {
//            totalNumber = map.get("c");
//        }
//        if(totalNumber ==0)
//            return;
//        page=(totalNumber%numberPage)==0?(totalNumber/numberPage):(totalNumber/numberPage+1);
//
//        for(long i=0;i<= page;i++)
//        {
//            sql = "SELECT id,activityCode,name,startDay,startHour,startMinute,endDay,endHour,endMinute,status,demo,attendCount,times,address,province,city,district,type,week_day,needs,signCount,img,createTime,tag,lng,lat,locked FROM volunteer_pu.activity WHERE  delStatus=0 and id >=(SELECT id FROM volunteer_pu.activity where delStatus=0 ORDER BY id LIMIT " + i * numberPage + ", 1) LIMIT " + numberPage;
//            List<Map<String, String>> list0 = this.queryNativeSql(sql);
//            for (Map<String, String> map : list0)
//            {
//                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(map));
//                importUser(jsonObject);
//            }
//        }

        String sql = "SELECT id,activityCode,name,startDay,startHour,startMinute,endDay,endHour,endMinute,status,demo,attendCount,times,address,province,city,district,type,week_day,needs,signCount,img,createTime,tag,lng,lat,locked,organization,createUser FROM volunteer_pu.activity WHERE  delStatus=0 and id =731";
        List<Map<String, String>> list0 = baseDAO.queryNativeSql(sql);
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list0));
        for(int i=0;i<jsonArray.size();i++)
        {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(jsonArray.get(i)));
            importActs(jsonObject);
        }
    }
    //导入活动
    private void importActs(JSONObject jsonObject)
    {
        Long id = jsonObject.getLong("id");
        String activityCode = jsonObject.getString("activityCode");            //活动名称
        String name = jsonObject.getString("name");            //活动名称
        String startDay = jsonObject.getString("startDay");            //活动名称
        String startHour = jsonObject.getString("startHour");            //活动名称
        String startMinute = jsonObject.getString("startMinute");            //活动名称
        String endDay = jsonObject.getString("endDay");            //活动名称
        String endHour= jsonObject.getString("endHour");            //活动简单
        String endMinute= jsonObject.getString("endMinute");            //图片
        int status= jsonObject.getIntValue("status");       //开始日期
        String demo= jsonObject.getString("demo");               //活动开展类型
        int attendCount= jsonObject.getIntValue("attendCount");         //活动地址
        Long times= jsonObject.getLong("times");            //标签
        String address= jsonObject.getString("address");         //周期
        String province= jsonObject.getString("province");         //周期
        String city= jsonObject.getString("city");         //周期
        String district= jsonObject.getString("district");         //周期
        int type= jsonObject.getIntValue("type");         //周期
        String weekDay= jsonObject.getString("week_day");         //周期
        int needs= jsonObject.getIntValue("needs");         //周期
        int signCount= jsonObject.getIntValue("signCount");         //周期
        String img= jsonObject.getString("img");         //周期
        String createTime= jsonObject.getString("createTime");         //周期
        String tag= jsonObject.getString("tag");         //周期
        String lng= jsonObject.getString("lng");         //周期
        String lat= jsonObject.getString("lat");         //周期
        int locked= jsonObject.getIntValue("locked");         //周期
        Long createUser= jsonObject.getLong("createUser");         //周期
        Long organization= jsonObject.getLong("organization");         //周期

        int scope= -1;           //签到误差范围

        Activity activity = new Activity();
        Volunteer volunteer = new Volunteer(Long.parseLong(this.volID_OLDID_NEWID.get(createUser)));
        Group group = new Group(Long.parseLong(this.orgID_OLDID_NEWID.get(organization)));
        activity.setApplys(signCount);
        activity.setTimes(times);
        activity.setAttends(attendCount);
        activity.setStatus(status);
        try
        {
            activity.setCreateTime(DateUtil.DefaultTimeFormatter.parse(createTime));
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        activity.setLocked(locked);
        activity.setActivityCode(activityCode);
        activity.setGroup(group);
        activity.setCreateUser(volunteer);
        activity.setMonitor(volunteer);
        activity.setCreateTime(Clock.DEFAULT.getCurrentDate());
        activity.setScope(scope);
        activity.setNeeds(needs);
        activity.setName(name);
        activity.setDemo(demo);
        activity.setImgs(img);
        activity.setType(type);
        activity.setStartTime(startDay + " " + startHour + ":" + startMinute + ":00");
        activity.setEndTime(endDay + " " + endHour + ":" + endMinute + ":00");
        activity.setAddress(address);
        activity.setTags(tag);
        activity.setWeekDay(weekDay);
        activity.setSelfGroup(0);
        activity.setApplys(0);
        activity.setTimes(0L);
        activity.setProvince(province);
        activity.setCity(city);
        activity.setDistrict(district);
        activity.setLng(Double.valueOf(lng));
        activity.setLat(Double.valueOf(lat));
        this.activityDao.save(activity);
        this.actID_OLDID_NEWID.put(String.valueOf(id), String.valueOf(activity.getId()));
    }
    /***********************************************************/





    /***********************************************************/
    //导入用户
    private void importMember()
    {
        long totalNumber = 0,numberPage = 2000,page = 0;
        String sql = "select count(id) as c from volunteer_pu.member where delStatus=0";
        List<Map<String, Long>> list = baseDAO.queryNativeSql(sql);
        for (Map<String, Long> map : list)
        {
            totalNumber = map.get("c");
        }
        if(totalNumber ==0)
            return;
        page=(totalNumber%numberPage)==0?(totalNumber/numberPage):(totalNumber/numberPage+1);

        for(long i=0;i<= page;i++)
        {
            sql = "SELECT id,volunteerCode,memberID,bundMobile,email,password,nickName,realName,headUrl,allTimes,birthday,sex,cardNo,censusRegister FROM volunteer_pu.member WHERE  delStatus=0 and id >=(SELECT id FROM volunteer_pu.member where delStatus=0 ORDER BY id LIMIT " + i * numberPage + ", 1) LIMIT " + numberPage;
            List<Map<String, String>> list0 = baseDAO.queryNativeSql(sql);
            for (Map<String, String> map : list0)
            {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(map));
                try
                {
                    importUser(jsonObject);
                } catch (Exception e)
                {
                    e.printStackTrace();
                    continue;
                }
            }
        }

//            String sql = "SELECT id,volunteerCode,memberID,bundMobile,email,password,nickName,realName,headUrl,allTimes,birthday,sex,cardNo,specialtyAddress,regDate FROM volunteer_pu.member WHERE  delStatus=0 and id =731";
//            List<Map<String, String>> list0 = this.queryNativeSql(sql);
//            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list0));
//            for(int i=0;i<jsonArray.size();i++)
//            {
//                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(jsonArray.get(i)));
//                importUser(jsonObject);
//            }

    }
    //导入User表、导入U_VOLUNTEER表
    private void importUser(JSONObject jsonObject)throws Exception
    {

        Long id = jsonObject.getLong("id");
        String key = "volunteers_OLDID_NEWID";
        if(this.redisClientTemplate.exists(key))
        {
            volID_OLDID_NEWID = JSON.parseObject(redisClientTemplate.get(key), Map.class);
            if(null != volID_OLDID_NEWID)
            {
                String newID = volID_OLDID_NEWID.get(String.valueOf(id));
                System.out.println(newID+"-------------->"  +id);
                if(null != newID && StringUtils.isNotBlank(newID))
                    return;
            }
        }

        String volunteerCode = jsonObject.getString("volunteerCode");
        String memberID = jsonObject.getString("memberID");
        String bundMobile = jsonObject.getString("bundMobile");
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
        String nickName = jsonObject.getString("nickName");
        String realName = jsonObject.getString("realName");
        String headUrl = jsonObject.getString("headUrl");
        Long allTimes = jsonObject.getLong("allTimes");
        String birthday = jsonObject.getString("birthday");
        String sex = jsonObject.getString("sex");
        String specialtyAddress = jsonObject.getString("specialtyAddress");
        String regDate = jsonObject.getString("regDate");
        String cardNo = jsonObject.getString("cardNo");

        User user = new User();
        if(StringUtils.isBlank(bundMobile))
        {
            Calendar cal = Calendar.getInstance();
            bundMobile = "2"+RandomStringUtils.random(10,String.valueOf(cal.getTimeInMillis())+"0123456987");
        }
        user.setMobile(bundMobile);
        user.setPassword(password);
        user.setRealName(realName);
        user.setNickName(nickName);
        user.setRoles("user");
        user.setEmail(email);
        user.setPlatform(2);
        user.setOldID(id);
        user.setOldMemberCode(memberID);
        try
        {
            if(StringUtils.isNotBlank(regDate))
                user.setCreateTime(DateUtil.DefaultTimeFormatter.parse(regDate));
            else
                user.setCreateTime(Clock.DEFAULT.getCurrentDate());
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        this.accountDao.save(user);

        //保存志愿者信息
        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(memberID);
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setUserId(user.getId());
        volunteer.setTimes(allTimes);
        volunteer.setHeadUrl(headUrl);
        volunteer.setVolunteerCode(volunteerCode);
        volunteer.setSex(sex);
        volunteer.setCardNO(cardNo);
        volunteer.setBirthDay(birthday);
        if(StringUtils.isNotBlank(specialtyAddress))
        {
            String[] address = specialtyAddress.split("-");
            volunteer.setResidenceAddress(specialtyAddress);
            if(address.length == 3)
            {
                volunteer.setProvince(address[0]);
                volunteer.setCity(address[1]);
                volunteer.setDistrict(address[2]);
            }
        }
        try
        {
            if(StringUtils.isNotBlank(regDate))
                volunteer.setCrateTime(DateUtil.DefaultTimeFormatter.parse(regDate));
            else
                volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        this.volunteerDao.save(volunteer);

        if(!this.redisClientTemplate.exists(key))
        {
            this.volID_OLDID_NEWID.put(String.valueOf(id), String.valueOf(volunteer.getId()));
            redisClientTemplate.setex(key,3600*24*30,JSON.toJSONString(this.volID_OLDID_NEWID));
        }
        else
        {
            volID_OLDID_NEWID = JSON.parseObject(redisClientTemplate.get(key), Map.class);
            this.volID_OLDID_NEWID.put(String.valueOf(id), String.valueOf(volunteer.getId()));
            redisClientTemplate.setex(key, 3600 * 24 * 30, JSON.toJSONString(this.volID_OLDID_NEWID));
        }
    }
    /***********************************************************/





    /***********************************************************/
    private void importGroup()
    {
        //        long totalNumber = 0,numberPage = 200000,page = 0;
//        String sql = "select count(id) as c from volunteer_pu.organization where delStatus=0";
//        List<Map<String, Long>> list = this.queryNativeSql(sql);
//        for (Map<String, Long> map : list)
//        {
//            totalNumber = map.get("c");
//        }
//        if(totalNumber ==0)
//            return;
//        page=(totalNumber%numberPage)==0?(totalNumber/numberPage):(totalNumber/numberPage+1);
//
//        for(long i=0;i<= page;i++)
//        {
//            sql = "SELECT id,groupCode,name,province,city,district,address,demo,phone,monitor,logo,createUser,create_time,createUser FROM volunteer_pu.organization WHERE  delStatus=0 and id >=(SELECT id FROM volunteer_pu.organization where delStatus=0 ORDER BY id LIMIT " + i * numberPage + ", 1) LIMIT " + numberPage;
//            List<Map<String, String>> list0 = this.queryNativeSql(sql);
//            for (Map<String, String> map : list0)
//            {
//                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(map));
//                importOrg(jsonObject);
//            }
//        }

        String sql = "SELECT id,groupCode,name,province,city,district,address,demo,phone,monitor,logo,create_time,createUser FROM volunteer_pu.organization WHERE  delStatus=0 and id = 170";
        List<Map<String, String>> list0 = baseDAO.queryNativeSql(sql);
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list0));
        for(int i=0;i<jsonArray.size();i++)
        {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(jsonArray.get(i)));
            importOrg(jsonObject);
        }
    }
    //导入组织
    private void importOrg(JSONObject jsonObject)
    {
        System.out.println("jsonObject------>"+jsonObject);
        Long id = jsonObject.getLong("id");
        String groupCode = jsonObject.getString("groupCode");
        String name = jsonObject.getString("name");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        String district = jsonObject.getString("district");
        String address = jsonObject.getString("address");
        String demo = jsonObject.getString("demo");
        String phone = jsonObject.getString("phone");
        String monitor = jsonObject.getString("monitor");
        String logo = jsonObject.getString("logo");
        String create_time = jsonObject.getString("create_time");
        String createUser = jsonObject.getString("createUser");

        Group group = new Group();
        group.setOldID(id);
        group.setName(name);
        group.setGroupCode(groupCode);
        group.setProvince(province);
        group.setCity(city);
        group.setDistrict(district);
        group.setRegAddress(address);
        group.setLogo(logo);
        group.setDemo(demo);
        group.setPhone(phone);
        group.setMonitor(monitor);
        group.setTimes(0L);
        group.setCreateUser(new Volunteer(1L));
        try
        {
            group.setCreateTime(DateUtil.DefaultTimeFormatter.parse(create_time));
        } catch (ParseException e)
        {
            e.printStackTrace();
        }

        this.groupDao.save(group);
        this.orgID_OLDID_NEWID.put(String.valueOf(id), String.valueOf(group.getId()));
    }
    /***********************************************************/



    //用户加入组织
    private void importMemberOrg()
    {

    }

    //导入个人的公益记录
    private void importSign()
    {

    }
    //导入活动的报名记录
    private void importActApply()
    {

    }
}
